<template>
  <div class="indicators-chart" id="indicators-chart"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from "vue";
import * as echarts from "echarts";
import { getTrafficIndicators } from "@/apis/TrafficIndicators";

const chart = ref<echarts.ECharts | null>(null);

// 初始化图表
const initChart = () => {
  nextTick(() => {
    const chartDom = document.getElementById("indicators-chart");
    if (!chartDom) return;

    chart.value = echarts.init(chartDom);
    const option = {
      tooltip: {
        trigger: "item",
        formatter: (params: any) => {
          const { value } = params;
          const titles = [
            "路网高延时运行时间占比",
            "路网拥堵路段里程比",
            "常发拥堵路段里程比",
            "路网高峰行程延时指数",
            "骨干道路运行速度偏差率",
            "高峰平均速度",
          ];

          return titles
            .map((title, index) => {
              let displayValue = value[index];
              // 处理不同指标的显示格式
              if (index === 0) {
                displayValue = displayValue.toFixed(2) + "%";
              } else if (index === 1 || index === 2 || index === 4) {
                displayValue = (displayValue * 100).toFixed(2) + "%";
              } else {
                displayValue = displayValue.toFixed(2);
              }
              return `${title}: ${displayValue}`;
            })
            .join("<br/>");
        },
      },
      radar: {
        indicator: [
          { name: "高延时占比", max: 1, axisLabel: { formatter: "{value}%" } },
          { name: "拥堵里程比", max: 0.1, axisLabel: { formatter: "{value}%" } },
          { name: "常发拥堵比", max: 0.1, axisLabel: { formatter: "{value}%" } },
          { name: "延时指数", max: 5 },
          { name: "速度偏差率", max: 1, axisLabel: { formatter: "{value}%" } },
          { name: "平均速度", max: 100, axisLabel: { formatter: "{value}km/h" } },
        ],
        center: ["50%", "50%"],
        radius: "55%",
        splitNumber: 5,
        shape: "polygon",
        axisName: {
          color: "#606266",
          fontSize: 13,
          formatter: (name: string, indicator: any) => {
            const value = indicator.value;
            let displayValue = "";

            switch (name) {
              case "高延时占比":
                displayValue = value ? value.toFixed(2) + "%" : "";
                break;
              case "拥堵里程比":
              case "常发拥堵比":
              case "速度偏差率":
                displayValue = value ? (value * 100).toFixed(2) + "%" : "";
                break;
              case "平均速度":
                displayValue = value ? value.toFixed(2) + "km/h" : "";
                break;
              default:
                displayValue = value ? value.toFixed(2) : "";
            }

            return `${name}\n${displayValue}`;
          },
        },
        splitLine: {
          lineStyle: {
            color: "#E4E7ED",
            type: "dashed",
          },
        },
        splitArea: {
          show: true,
          areaStyle: {
            color: ["rgba(255, 255, 255, 0.3)", "rgba(245, 247, 250, 0.3)"],
          },
        },
        axisLine: {
          lineStyle: {
            color: "#DCDFE6",
          },
        },
      },
      series: [
        {
          type: "radar",
          symbol: "none",
          emphasis: {
            lineStyle: {
              width: 4,
            },
            areaStyle: {
              color: "rgba(64, 158, 255, 0.8)",
            },
          },
          data: [
            {
              value: [0, 0, 0, 0, 0, 0],
              name: "交通指标",
              lineStyle: {
                width: 2,
                color: "#409EFF",
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color: "rgba(64, 158, 255, 0.7)",
                  },
                  {
                    offset: 1,
                    color: "rgba(64, 158, 255, 0.2)",
                  },
                ]),
              },
            },
          ],
        },
      ],
    };

    chart.value.setOption(option);
  });
};

// 获取指标数据
const fetchIndicators = async () => {
  try {
    const { success, data } = await getTrafficIndicators();
    if (success && chart.value) {
      const currentValues = data.indicators.map((item: any) => item.value);

      // 更新图表数据
      chart.value.setOption({
        series: [
          {
            data: [
              {
                value: currentValues,
                name: "交通指标",
              },
            ],
          },
        ],
      });
    }
  } catch (error) {
    console.error("获取交通指标数据失败:", error);
  }
};

// 处理窗口大小变化
const handleResize = () => {
  nextTick(() => {
    chart.value?.resize();
  });
};

onMounted(() => {
  initChart();
  fetchIndicators();
  window.addEventListener("resize", handleResize);
});

onUnmounted(() => {
  chart.value?.dispose();
  window.removeEventListener("resize", handleResize);
});
</script>

<style lang="scss" scoped>
.indicators-chart {
  width: 100%;
  height: 100%;
}
</style>
